<template>
    <div>
        <el-breadcrumb separator="/" class="m-b-20">
            <el-breadcrumb-item><a href="/">后台首页</a></el-breadcrumb-item>
            <el-breadcrumb-item>图片管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-button type="primary" @click="dialog = true">上传图片</el-button>
        <el-dialog title="上传图片" v-model="dialog" custom-class="dialog-upload-image">
            <el-upload :action="uploadImage" :show-file-list="false" :on-success="handleCoverSuccess"
                :before-upload="beforeImageUpload">
                <img v-if="coverUrl" :src="coverUrl" class="cover">
                <i v-else class="el-icon-plus cover"></i>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传 JPG / PNG / BMP / WEBP 文件，且不超过 2MB
                    </div>
                </template>
            </el-upload>
            <el-input type="text" v-model="url"></el-input>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="success">复制</el-button>
                    <el-button @click="dialog = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {
        __IMAGE__
    } from '@/main'

    export default {
        name: 'Image',
        data() {
            return {
                dialog: false,
                tableData: [],
                uploadImage: '',
                coverUrl: '',
                url: ''
            }
        },
        created() {
            this.uploadImage = __IMAGE__
        },
        methods: {
            handleCoverSuccess(res, file) {
                this.coverUrl = URL.createObjectURL(file.raw)
                this.url = res.data
            },
            beforeImageUpload(file) {
                if (['image/jpeg', 'image/bmp', 'image/png', 'image/webp'].indexOf(file
                        .type) == -1) {
                    this.$message.error({
                        message: '请上传正确的图片格式！',
                        type: 'error',
                        offset: 80
                    })
                    return false
                }

                const size = file.size / 1024 / 1024 < 2
                if (!size) {
                    this.$message.error({
                        message: '图片大小不能超过 2MB！',
                        type: 'error',
                        offset: 80
                    })
                    return false
                }
            }
        }
    }
</script>

<style scoped>
</style>